import json
import os
import requests


# 酷狗音乐爬取
# url = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19109252567465037509_1673923211507&dfid=1JcxvS1M6A0w1kg5QN27Qg8Z&appid=1014&mid=56a6e2cf827fddbc0adea5dc55452c07&platid=4&encode_album_audio_id=4fi8fqac&_=1673923211508'
# headers = {
#     'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36'
# }
# res = requests.get(url,headers = headers)
# if res.status_code != 200:
#   print('请求失败')
# else:
#   music_url = json.loads(res.text.strip(');').strip('jQuery19109252567465037509_1673923211507('))['data']['play_url']
#   name = os.path.basename(music_url)
#   f = open(f'music/{name}','wb')
#   music = requests.get(music_url)
#   f.write(music.content)
#   f.close()

# 网易云音乐
url = 'https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token='
headers = {
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36'
}
data = {
    'params':'DtX6iPtcBnZB3zE5fFuHcKEj9ZQxtRF3lFjSh5uFSBUJNpIfRViN9Hl8Y+sL+WXbQZtS3N15D7qZLsXYE4Taoc1z4breCupqVTZR+RUzdljFK0e30fU9xdl/zBlIK6uxbuj/K43VSARG4xWXB1LXmg==',
    'encSecKey':'d0e7b3f2f6f70a22dbda62cee1b481e9b657cd3aeb9c38d67ade6c47554dac55daac60d009233d1054db34647f9dc97446d113f422f1bc1424277df3f5d5db8eb32aca69a898f31aef40906457317661f62caef030792d8faa1495b79b099e28758a98e64ac244dfe405b0ab19ce0ca4a5da359e5e69384b9c8ba4503da3202f'
}
res = requests.post(url,headers = headers,data=data)
if res.status_code != 200:
    print('请求失败')
else:
    music_url = json.loads(res.text)['data'][0]['url']
    name = os.path.basename(music_url)
    f = open(f'music/{name}','wb')
    music = requests.get(music_url)
    f.write(music.content)
    f.close()